package collectionDemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: Jie
 * @Date: 2019/5/10 1:25
 * @Function : 并发操作 问题
 */
public class VectorList {

    static CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>();
//    static ArrayList<Integer> list = new ArrayList<Integer>();
    public static void main(String[] args) {
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        Thread thread1 = new Thread(){
            public void run() {
                for (int i = 0; i < list.size(); i++) {
                    int size = ((CopyOnWriteArrayList<Integer>) list.clone()).size();
                    System.out.println(list.get(i)+"  size=="+size);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


//                synchronized (VectorList.class){
//                    Iterator<Integer> iterator = list.iterator();
//                    while(iterator.hasNext()){
//                        Integer integer = iterator.next();
//                        System.out.println(integer);
//                        try {
//                            Thread.sleep(1000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }

            };
        };
        Thread thread2 = new Thread(){
            public void run() {
                synchronized (VectorList.class){
                    Iterator<Integer> iterator = list.iterator();
                    while(iterator.hasNext()){
                        Integer integer = iterator.next();
                        if(integer==2) {
                            List<Integer>temp = new ArrayList<Integer>();
//                            boolean remove = list.remove(integer);
                            temp.add(2);
                            temp.add(3);
                            boolean remove = list.removeAll(temp);
                            System.out.println("thread 2 remove res==" +remove);
                        }
//                        iterator.remove();
                    }
                }

            };
        };
        thread1.start();
        thread2.start();
    }
}
